package kadledav.backend.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import kadledav.backend.model.AbstractBO;

public class GenericDAO<T extends AbstractBO> {

	@PersistenceContext
	protected EntityManager entityManager;

	private Class<T> entityClass;

	public GenericDAO(Class<T> clazz) {
		entityClass = clazz;

	}

	public void insert(T t) {
		entityManager.persist(t);
	}

	public void remove(T t) {
		entityManager.remove(entityManager.merge(t));
	}

	public void update(T t) {
		entityManager.merge(t);
	}

	public T findById(int id) throws EntityNotFoundException {
		T result = entityManager.find(entityClass, id);
		if (result == null) {
			throw new EntityNotFoundException();
		}
		return result;
	}

	public List<T> getAll() {
		TypedQuery<T> q = entityManager.createQuery("SELECT e FROM " + entityClass.getSimpleName() + " e", entityClass);
		return q.getResultList();
	}

}